#define DEBUG
#include <cstdio>

using namespace std;

typedef unsigned long long ull;
const int maxn=100000;
const ull seed=10000007;

int max(int a, int b) {
	return a>b ? a : b;
}

class HashTable {
	public:
		static const int size=19491001;
		ull key[size+1];
		int val[size+1];

		void add(ull k, int v) {
			int p=k%size;
			for (; key[p]; p=(p+1)%size) {
				if (key[p]==k) {
					val[p]+=v;
					return;
				}
			}
			key[p]=k, val[p]=v;
		}

		int get(ull k) {
			int p=k%size;
			for (; key[p]; p=(p+1)%size) {
				if (key[p]==k) {
					return val[p];
				}
			}
			return 0;
		}
};

ull powt[maxn*2+1];

ull genKey(int alen, ull a, int blen, ull b) {
	return a*powt[blen+1]+b*powt[1]+alen+blen+1;
}

ull addToHash(int o, int son[][2], HashTable &t) {
	static int size[maxn+1];
	size[o] = 1;
	if (o) {
		ull a = addToHash(son[o][0], son, t), b = addToHash(son[o][1], son, t), ret;
		size[o] += size[son[o][0]]+size[son[o][1]];
		t.add(ret = genKey(size[son[o][0]], a, size[son[o][1]], b), 1);
		return ret;
	} else {
		return 1;
	}
}

int getAns(int o, int son[][2], HashTable &t) {
	static int size[maxn+1];
	static ull key[maxn+1];
	size[o] = 1;
	int ret=0;
	if (o) {
		ret += getAns(son[o][0], son, t)+getAns(son[o][1], son, t);
		size[o] += size[son[o][0]]+size[son[o][1]];
		ret += t.get(key[o]=genKey(size[son[o][0]], key[son[o][0]], size[son[o][1]], key[son[o][1]]));
	} else {
		key[o] = 1;
	}
	return ret;
}

int main() {
#ifdef DEBUG
	freopen("src.in", "r", stdin);
	freopen("src.out", "w", stdout);
#endif

	static int a[maxn+1][2], b[maxn+1][2];
	int n, m;
	scanf("%d %d", &n, &m);
	for (int i=1; i<=n; i++) {
		scanf("%d %d", a[i], a[i]+1);
		a[i][0] = a[i][0]>0 ? a[i][0] : 0;
		a[i][1] = a[i][1]>0 ? a[i][1] : 0;
	}
	for (int i=1; i<=m; i++) {
		scanf("%d %d", b[i], b[i]+1);
		b[i][0] = b[i][0]>0 ? b[i][0] : 0;
		b[i][1] = b[i][1]>0 ? b[i][1] : 0;
	}

	powt[0] = 1;
	powt[1] = seed;
	for (int i=1; i<=max(n, m)*2; i++) {
		powt[i] = powt[i-1]*powt[1];
	}

	static HashTable table;
	addToHash(1, b, table);

	printf("%d", getAns(1, a, table));

	fclose(stdin);
	fclose(stdout);
	return 0;
}
